<template>
    <div class="container">
        <el-form class="form_box" ref="formRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="任务标题" prop="Title">
                <el-input class="title_inp" v-model="form.Title" clearable :show-word-limit="true" maxlength="15" />
            </el-form-item>
            <el-form-item label="选择群聊" class="item_margin" required :show-message="false">
                <ZWSelectGroup v-model="form" :option="modelOption" :select-disabled="selectDisabled" :http-request="getCustGroupchatList" >
                    <template #radioOption>
                        <el-radio :label="modelOption.allLabel">
                            <span>全部外部群</span>
                            <el-tooltip content="群聊中包含“我”的全部外部群聊。" placement="top">
                                <el-icon class="group-tootip-icon" color="#ccc" ><QuestionFilled /></el-icon>
                            </el-tooltip>
                        </el-radio>
                        <el-radio :label="modelOption.selectLabel">选择外部群</el-radio>
                    </template>
                </ZWSelectGroup>
            </el-form-item>
            <el-form-item label="排除条件" prop="ExclusionType">
                <div class="condition">
                    <div class="condition_item"> 排除包含以下条件的群成员 </div>
                    <div class="condition_item">
                        <div class="condition_item_name">类型</div>
                        <el-checkbox-group v-model="form.ExclusionType">
                            <el-checkbox :label="11" name="type">群主</el-checkbox>
                            <el-checkbox :label="12">群管理</el-checkbox>
                            <el-checkbox :label="21">男性</el-checkbox>
                            <el-checkbox :label="22">女性</el-checkbox>
                            <el-checkbox :label="23">未知性别</el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div class="condition_item">
                        <div class="condition_item_name">昵称关键词</div>
                        <div class="condition_content">
                            <el-input class="condition_inp" ref="InputRef" v-model="state.ExclusionNickName" maxlength="50"
                                :show-word-limit="true" clearable placeholder="请输入关键词，按enter键创建~不超过50字"
                                @keyup.enter="onExclusionNickName" @blur="onExclusionNickName" />
                            <el-tag class="nickname" v-for="(tag, index) in form.ExclusionNickName" type="info" :key="tag"
                                closable :disable-transitions="false" @close="onDelExclusionNickName(index)">
                                {{ tag }}
                            </el-tag>
                        </div>
                    </div>
                    <div class="condition_item">
                        <div class="condition_item_name">企业名称关键词</div>
                        <div class="condition_content">
                            <el-input class="condition_inp" ref="InputRef" v-model="state.ExclusionCompanyName"
                                maxlength="50" :show-word-limit="true" clearable placeholder="请输入关键词，按enter键创建~不超过50字"
                                @keyup.enter="onExclusionCompanyName" @blur="onExclusionCompanyName" />
                            <el-tag class="nickname" v-for="(tag, index) in form.ExclusionCompanyName" type="info"
                                :key="tag" closable :disable-transitions="false" @close="onDelExclusionCompanyName(index)">
                                {{ tag }}
                            </el-tag>
                        </div>
                    </div>
                    <div class="estimated-number" >(预计添加好友数: <span>{{ state.EstimatedNumber }}</span>)</div>
                </div>
            </el-form-item>
            <el-form-item label="验证消息" prop="VerifyMessage">
                <el-input v-model="form.VerifyMessage" type="textarea" maxlength="50" placeholder="请输入验证消息，最多支持50个字"
                    :show-word-limit="true" :rows="4" />
            </el-form-item>
            <el-form-item label="客户标签">
                <div>
                    <ZWRenderTags v-model:tags="form.CustTagList" @openMore="onOpenTag"></ZWRenderTags >
                    <el-button @click="onOpenTag">选择标签</el-button>
                </div>
            </el-form-item>
            <el-form-item label="自动备注" class="auto_remarks">
                <el-switch v-model="form.AutoRemarks" />
            </el-form-item>
            <el-form-item v-if="form.AutoRemarks" prop="AutoRemarksMsg">
                <el-input id="inputId" v-model="form.AutoRemarksMsg" type="textarea" maxlength="50" placeholder="请添加自动备注内容"
                    :show-word-limit="true" :rows="4" />
                <div class="remarks_btn">
                    <el-button @click="onSetInpCursor('[添加日期]')">添加日期</el-button>
                    <el-button @click="onSetInpCursor('[昵称]')">昵称</el-button>
                </div>
            </el-form-item>
            <div class="desc">开启后，将对添加的好友在企微中进行备注。</div>
            <el-form-item>
                <el-button @click="onRouteBack">取消</el-button>
                <el-button type="primary" @click="onSubmit(formRef)">确定</el-button>
            </el-form-item>
        </el-form>
    </div>
    <ZWSelectLabel ref="ZWSelectLabelRef" v-model="labelVisiable" @submit="getCUstTag" />
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick, onMounted, watchEffect } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

import ZWSelectLabel from '@renderer/components/win/ZWSelectLabel/ZWSelectLabel.vue'
import ZWRenderTags from '@renderer/components/win/ZWSelectLabel/ZWRenderTags.vue'
import ZWSelectGroup from '@renderer/components/win/ZWSelectGroup/ZWSelectGroup.vue'
import { GROUP_TYPE_MAP } from '@renderer/components/win/ZWSelectGroup/enum'
import { putMakeGroupFriend, getMakeGroupFriendDetail, getCustGroupchatList, getEstimatedNumber } from '@renderer/ajax/api/addGroupBuddy'


const router = useRouter()
const route = useRoute()
const formRef = ref<any>(null)
// 存放展示的数据
const state = reactive({
    CustTagList: [],
    ExclusionNickName: '',
    ExclusionCompanyName: '',
    EstimatedNumber: 0
})
const modelOption = reactive({
    type: 'isallGroupchat',
    selected: 'GroupChatList',
    allLabel: true,
    selectLabel: false
})
// 禁用内部群
const selectDisabled = reactive([{
    key: 'selectType',
    value: GROUP_TYPE_MAP['内部群'],
    defaultSelected: GROUP_TYPE_MAP['外部群']
}])
// 提交表单
const form = reactive({
    Id: 0, // ID 不为0 为编辑
    Title: '', // 标题
    isallGroupchat: true,
    GroupChatList: [],
    ExclusionType: [],
    ExclusionNickName: [],
    ExclusionCompanyName: [],
    VerifyMessage: '', // 验证信息
    CustTagList: [],
    AutoRemarks: true, // 自动备注
    AutoRemarksMsg: '' // 自动备注内容
})
const groupValidator = (rules, value, callback) => {
    if (form.isallGroupchat) {
        callback()
    } else {
        if (form.GroupChatList.length) {
            callback()
        } else {
            callback(new Error('请选择群聊'))
        }
    }
}
const rules = reactive<any>({
    Title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
    GroupChatList: [{ required: true, validator: groupValidator, trigger: 'blur' }],
    ExclusionType: [{ required: true, message: '请选择排除条件', trigger: 'change' }],
    VerifyMessage: [{ required: true, message: '请输入验证消息', trigger: 'blur' }],
    AutoRemarksMsg: [{ required: true, message: '请添加自动备注内容', trigger: 'blur' }]
})


/* ----------------------------预计添加好友数-start---------------------------- */
/**
 * 获取预计添加好友数量
 */
const computedEstimatedNumber = async () => {
    try {
        const params = {
            // 是否所有群
            isallGroupchat: form.isallGroupchat,
            // 群聊id
            groupChatList: form.GroupChatList.map(item => item.id),
            // 排除条件类型
            exclusionType: form.ExclusionType,
            // 昵称关键字
            exclusionNickName: form.ExclusionNickName,
            // 企业关键字
            exclusionCompanyName: form.ExclusionCompanyName,
        }
        const res: any = await getEstimatedNumber(params)
        console.log('res: ', res);
        state.EstimatedNumber = res
    } catch {
        state.EstimatedNumber = 0
    }
}

watchEffect(() => {
    computedEstimatedNumber()
})
/* ----------------------------预计添加好友数-end---------------------------- */


// 返回
const onRouteBack = () => {
    router.back()
}
// 提交
const onSubmit = (formEl: any) => {
    console.log('submit!')
    formEl.validate(async (valid: any) => {
        if (valid) {
            const params = {
                ...form,
                GroupChatList: form.GroupChatList.map(item => item.id),
                CustTagList: form.CustTagList.map(item => item.Id)
            }

            // 点击保存时校验一次人数
            await computedEstimatedNumber()
            if (!state.EstimatedNumber) {
                ElMessageBox.alert('请选择需要添加的群好友！', '提示', {
                    confirmButtonText: '好的',
                })
                return
            }

            const res = await putMakeGroupFriend(params)
            const message = form.Id ? '编辑任务成功' : '新建任务成功'
            ElMessage.success(message)
            router.back()
        } else {
            console.log('submit fail!')
            return false
        }
    })
}
// 添加关键字
const onExclusionNickName = () => {
    if(form.ExclusionNickName.includes(state.ExclusionNickName)) {
        ElMessage.warning('关键字不能重复')
        return
    }
    if (state.ExclusionNickName) {
        form.ExclusionNickName.push(state.ExclusionNickName)
    }
    state.ExclusionNickName = ''
}
// 删除关键字
const onDelExclusionNickName = (index: number) => {
    form.ExclusionNickName.splice(index, 1)
}
// 添加企业关键字
const onExclusionCompanyName = () => {
    if(form.ExclusionCompanyName.includes(state.ExclusionCompanyName)) {
        ElMessage.warning('关键字不能重复')
        return
    }
    if (state.ExclusionCompanyName) {
        form.ExclusionCompanyName.push(state.ExclusionCompanyName)
    }
    state.ExclusionCompanyName = ''
}
// 删除企业关键字
const onDelExclusionCompanyName = (index: number) => {
    form.ExclusionCompanyName.splice(index, 1)
}

/* ----------------------------选择标签-start---------------------------- */
// 选择标签
const ZWSelectLabelRef = ref<any>(null)
const labelVisiable = ref(false)
const onOpenTag = () => {
    ZWSelectLabelRef.value.open(form.CustTagList)
}
// 获取标签
const getCUstTag = (v: any) => {
    form.CustTagList = v
}
/* ----------------------------选择标签-end---------------------------- */

// 添加备注
const onSetInpCursor = (v: any) => {
    const ElRef: any = document.getElementById('inputId')
    const inpIndex = ElRef.selectionStart
    const start = `${form.AutoRemarksMsg.substring(0, inpIndex)}${v}`
    const end = form.AutoRemarksMsg.substring(inpIndex, form.AutoRemarksMsg.length)
    form.AutoRemarksMsg = `${start}${end}`
    ElRef.focus()
    nextTick(() => {
        ElRef.selectionStart = start.length
        ElRef.selectionEnd = start.length
    })
}

const onLook = async () => {
    const res: any = await getMakeGroupFriendDetail({ Id: route.query.id })
    form.Id = res.Id // ID 不为0 为编辑
    form.Title = res.Title // 标题
    form.GroupChatList = res.GroupChatList
    form.isallGroupchat = !!res.isallGroupchat
    form.ExclusionType = res.ExclusionType
    form.ExclusionNickName = res.ExclusionNickName
    form.ExclusionCompanyName = res.ExclusionCompanyName
    form.VerifyMessage = res.VerifyMessage // 验证信息
    form.CustTagList = res.CustTagList
    form.AutoRemarks = res.AutoRemarks // 自动备注
    form.AutoRemarksMsg = res.AutoRemarksMsg // 自动备注内容
}
onMounted(() => {
    route.query.id && onLook()
})

</script>

<style scoped lang="scss">
.title_inp {
    width: 300px;
}

.table_box {
    width: 100%;
    border: 1px solid #dcdfe6;

    .btn {
        padding: 0;
    }
}

.zdy_btn {
    padding: 0;
}

.upload_desc {
    margin-top: 10px;
}

.container {
    background: #fff;
    padding: 16px;

    .form_box {
        width: 60%;

        .el-form-item {
            .el-form-item__content {
                width: 100%;
            }
        }
    }

    .num {
        color: #1432f5;
    }

    .clear {
        margin-left: 5px;
        cursor: pointer;

        &:hover {
            color: red;
        }
    }

    .item_margin {
        margin-bottom: 0;
    }

    .download {
        margin-left: 10px;
        color: #1432f5;
        cursor: pointer;
    }
}

.mobile_all {
    background: red;

    :deep(.el-textarea__inner) {
        border-radius: 0;
        cursor: default;

        &:hover {
            border: none;
        }
    }
}

.condition {
    flex: 1;

    .condition_item {
        margin-bottom: 10px;
        display: flex;
        font-size: 12px;

        .condition_inp {
            margin-bottom: 10px;
        }

        .condition_item_name {
            min-width: 100px;
            color: #b3b2b3;
        }

        .condition_content {
            flex: 1;
        }
    }
}

.nickname {
    margin-right: 10px;
}

.tag_list {
    margin-bottom: 10px;
}

.remarks_btn {
    margin-top: 10px;
}

.desc {
    padding-left: 120px;
    margin-bottom: 18px;
    font-size: 12px;
    color: #999;
}

:deep(.el-form-item__content) {
    min-width: auto;
}

.estimated-number {
    line-height: normal;
    color: var(--el-color-primary);
}

.group-tootip-icon {
    display: inline-block;
    height: 32px;
    line-height: 32px;
    vertical-align: middle;
    margin-left: 4px;
}

:deep(.render-tags) {
    margin-bottom: 12px;
}
</style>
